﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;

namespace MingYuanYun.Utility
{
    /// <summary>
    /// 应用类，封装常用的帮助方法
    /// </summary>
    public class Utils
    {
        /// <summary>
        /// MD5加密字符串
        /// </summary>
        /// <param name="inputText"></param>
        /// <returns>返回大写的MD5字符串</returns>
        public static string Md5(string inputText)
        {
            using (var md5 = MD5.Create())
            {
                var result = md5.ComputeHash(Encoding.UTF8.GetBytes(inputText));
                var strResult = BitConverter.ToString(result);
                return strResult.Replace("-", "");
            }
        }

        /// <summary>
        /// 将对象序列化成JSON
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectToJson(object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }

        /// <summary>
        /// 从JSON反序列化为对象
        /// </summary>
        /// <typeparam name="TReturn"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static TReturn JsonToObject<TReturn>(string json)
        {
            return JsonConvert.DeserializeObject<TReturn>(json);
        }

        /// <summary>
        /// 创建文件目录
        /// </summary>
        /// <param name="dir"></param>
        public static void CreateDirectory(string dir)
        {
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filename"></param>
        public static void DeleteFile(string filename)
        {
            if (File.Exists(filename))
            {
                File.Delete(filename);
            }
        }
    }
}
